<template>
  <div>
    <h2>我的购物车</h2>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item to="/MemberMain">主页</el-breadcrumb-item>
      <el-breadcrumb-item>购物车</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card style="margin-top: 20px;">
      <el-table
          :data="cartList"
          style="width: 100%;"
          @selection-change="handleSelectionChange"
          ref="tableRef"
          border
          v-loading="loading"
          empty-text="购物车为空"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="goodsName" label="商品名称" />
        <el-table-column prop="goodsPrice" label="单价(元)" />
        <el-table-column prop="mount" label="数量" />
        <el-table-column label="小计">
          <template #default="scope">
            {{ (scope.row.goodsPrice * scope.row.mount).toFixed(2) }} 元
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="danger" size="small" @click="removeFromCart(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="text-align: right; margin-top: 20px;">
        <strong>已选商品总计：{{ selectedTotalPrice }} 元</strong>
        <el-button type="success" @click="checkout" style="margin-left: 15px;">结算</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const cartList = ref([])
const selectedItems = ref([]) // 用于存储选中的商品
const loading = ref(false)

const loadCartData = () => {
  loading.value = true
  axios.get('/server/cart/list', {
    headers: {
      'Authorization': localStorage.getItem('token')
    }
  })
      .then(res => {
        if (res.data.code === 200) {
          cartList.value = res.data.data || []
        } else {
          ElMessage.error(res.data.message || '加载购物车失败')
        }
      })
      .catch(() => {
        ElMessage.error('请求失败，无法加载购物车')
      })
      .finally(() => {
        loading.value = false
      })
}

onMounted(() => {
  loadCartData()
})

// 处理选择变化
const handleSelectionChange = (val) => {
  selectedItems.value = val // 更新选中的商品
}

// 计算已选商品的总价
const selectedTotalPrice = computed(() => {
  return selectedItems.value.reduce((sum, item) => sum + item.goodsPrice * item.mount, 0).toFixed(2)
})

// 从购物车中移除商品
const removeFromCart = (item) => {
  axios.delete('/server/cart/remove', {
    params: { id: item.id },
    headers: {
      'Authorization': localStorage.getItem('token')
    }
  })
      .then(res => {
        if (res.data.code === 200) {
          ElMessage.success('已移除该商品')
          loadCartData() // 重新加载购物车
        } else {
          ElMessage.error(res.data.message || '移除失败')
        }
      })
      .catch(() => {
        ElMessage.error('请求出错，移除失败')
      })
}

// 结算
const checkout = () => {
  if (!selectedItems.value.length) {
    ElMessage.warning('请先选择要结算的商品')
    return
  }

  // 确保传递给后端的数据格式正确，符合 Cart 对象的结构
  const formattedItems = selectedItems.value.map(item => ({
    id: item.id,
    gid: item.gid,              // 商品ID
    goodsName: item.goodsName,   // 商品名称
    goodsPrice: item.goodsPrice, // 商品单价
    mount: item.mount            // 商品数量
  }))

  // 发送选中的商品数据到后端进行结算
  axios.post('/server/goodsOrder/creat', formattedItems, {
    headers: {
      'Authorization': localStorage.getItem('token')
    }
  }).then(res => {
    if (res.data.code === 200) {
      ElMessage.success('结算成功')
      router.push('/MemberMain/GoodsOrderInfo')  // 跳转到订单信息页面
    } else {
      ElMessage.error('结算失败: ' + res.data.message)
    }
  }).catch(err => {
    ElMessage.error('请求失败，请稍后再试')
  })
}

</script>

<style scoped>
h2 {
  margin-bottom: 10px;
}
</style>
